package com.prs.crm.service.sale.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.Set;

import com.prs.crm.context.Constrains;
import com.prs.crm.dao.sale.RetrunsDao;
import com.prs.crm.domain.flow.WorkFlowProcess;
import com.prs.crm.domain.sale.Returns;
import com.prs.crm.domain.sale.ReturnsDetail;
import com.prs.crm.domain.sale.SalesContract;
import com.prs.crm.domain.sale.SalesContractDetail;
import com.prs.crm.domain.sale.SalesShippingDetail;
import com.prs.crm.domain.stock.Product;
import com.prs.crm.domain.stock.ProductStore;
import com.prs.crm.service.impl.FlowServiceImpl;
import com.prs.crm.service.sale.ReturnsService;
import com.prs.crm.service.sale.SalesContractService;
import com.prs.crm.service.sale.SalesShippingDetailService;
import com.prs.crm.service.stock.ProductStoreService;

public class ReturnsServiceImpl extends FlowServiceImpl<Returns, RetrunsDao>
		implements ReturnsService {

	private ReturnsService returnsService;
	private ProductStoreService productStoreService;

	// private SalesContractService salesContractService;

	public ProductStoreService getProductStoreService() {
		return productStoreService;
	}

	public void setProductStoreService(ProductStoreService productStoreService) {
		this.productStoreService = productStoreService;
	}

	@Override
	public SalesContractDetail getSalesContractDetail(SalesContract sc,
			Product product) {
		return this.getDao().getSalesContractDetail(sc, product);
	}

	private SalesContractService salesContractService;
	private SalesShippingDetailService salesShippingDetailService;

	@Override
	public void onProcessEnd(WorkFlowProcess process) {
		super.onProcessEnd(process);
		Returns project = this.getProcessEntity(process);
		SalesContract contract = project.getSalesContract();
		Set<ReturnsDetail> returnsDetails = project.getDetails();
		if (process.getResult() == Constrains.WORKFLOWPROCESS_RESULT_PASS) {
			//System.out.println("come");
			for (ReturnsDetail detail : returnsDetails) {
				if (detail.getDetailsAll() != null
						&& !detail.getDetailsAll().trim().equals("")) {
					String[] details = detail.getDetailsAll().trim().split(",");
					//System.out.println(detail.getDetailsAll()+"   detail.getDetailsAll()");
					for (int c = 0; c < details.length; c++) {
						String[] values = details[c].trim().split("p");
						SalesShippingDetail salesShippingDetail = this
								.getSalesShippingDetailService().get(
										Integer.parseInt(values[1].trim()));
						//System.out.println(salesShippingDetail.getId()+"   id");

						String batchString = salesShippingDetail.getDetail();
						String[] batchdetail = batchString.split(",");
						//System.out.println(batchString+"   batchString'");
						String newbatchde = "";
						int d = 0;
						boolean asdf = false;
						for (int i = 0; i < batchdetail.length; i++) {
							//System.out.println(batchdetail[i]+"   batchdetail ");
							String string = batchdetail[i];
							if (Integer.parseInt(values[0].trim()) > d) {
								System.out.println(string+"           string1");
								String[] batchAndNum = string.split("p");
								ProductStore productStore = this.getProductStoreService().get(Integer.parseInt(batchAndNum[0]));
								//System.out.println(productStore.getId());
								if (Integer.parseInt(batchAndNum[1]) >= (Integer.parseInt(values[0].trim())-d)) {
									productStore.setProductNum(productStore
											.getProductNum()
											+ (Integer.parseInt(values[0].trim()) - d));
									newbatchde = newbatchde
											+ productStore.getId()
											+ "p"
											+ (Integer.parseInt(batchAndNum[1])
													- Integer.parseInt(values[0].trim()) + d)
											+ ",";
									d = d + Integer.parseInt(values[0].trim());
									//System.out.println("a");
									asdf = true;
								} else {
									System.out.println(string+"       string2:");
									productStore.setProductNum(productStore
											.getProductNum()
											+ Integer.parseInt(batchAndNum[1]));
									d = d + Integer.parseInt(batchAndNum[1]);
									newbatchde = newbatchde + productStore.getId()
											+ "p" + 0 + ",";
									//System.out.println("b");
								}
								this.getProductStoreService()
										.save(productStore);
							}
							if (asdf && (i + 1) < batchdetail.length) {
								newbatchde = newbatchde + batchdetail[i + 1]
										+ ",";
							}
							salesShippingDetail.setDetail(newbatchde);

						}
						this.getSalesShippingDetailService().save(
								salesShippingDetail);
					}

				}
			}

		} else {
			System.out.println("pass");
			for (ReturnsDetail returnsDetail : returnsDetails) {
				// for (SalesShippingDetail salesShippingDetail :
				// salesShippingDetails) {
				// if (returnsDetail.getProduct() == salesShippingDetail
				// .getProduct()) {
				//
				// salesShippingDetail.setOutNum(salesShippingDetail
				// .getOutNum()
				// - returnsDetail.getReturnNum());
				// salesShippingDetail.setOutState(0);
				// }
				// }
				for (SalesContractDetail contractDetail : contract.getDetails()) {
					if (contractDetail.getProduct() == returnsDetail
							.getProduct()) {
						contractDetail.setReturnNum(contractDetail
								.getReturnNum()
								- returnsDetail.getReturnNum());
						contractDetail.setReturnSate(0);
					}
				}
				String[] details = returnsDetail.getDetailsAll().trim().split(
						",");

				for (int c = 0; c < details.length; c++) {
					String[] values = details[c].trim().split("p");
					SalesShippingDetail salesShippingDetail = this
							.getSalesShippingDetailService().get(
									Integer.parseInt(values[1].trim()));
					salesShippingDetail.setRetruenNum(salesShippingDetail
							.getRetruenNum()
							- Integer.parseInt(values[0].trim()));

					salesShippingDetail.setRetruenState(0);
					this.getSalesShippingDetailService().save(
							salesShippingDetail);

				}

			}
			contract.setReturnState(0);
			salesContractService.save(contract);
		}

	}

	@Override
	public void saveReturns(Returns returns, Product[] products,
			String[] pronames, Double[] originalCosts, Double[] nowCosts,
			Integer[] returnsNums, Double[] rebates, String[] totalPrices,
			Integer[] returnResviceNum, String[] detailAll) {
		boolean returnstate = true;
		SalesContract salesContract = returns.getSalesContract();
		Set<SalesContractDetail> salesContractDetails = salesContract
				.getDetails();
		for (int i = 0; i < pronames.length; i++) {
			ReturnsDetail detail = new ReturnsDetail();
			detail.setName(products[i].getName());
			detail.setOriginalCost(originalCosts[i]);
			detail.setNowCost(nowCosts[i]);
			detail.setReturnNum(returnsNums[i]);
			detail.setRebate(rebates[i]);
			detail.setProduct(products[i]);
			detail.setTotalPrice(Double.parseDouble(totalPrices[i]));
			detail.setDetailsAll(detailAll[i]);
			detail.setReallyNum(returnResviceNum[i]);
			returns.addDetail(detail);
			for (SalesContractDetail salesContractDetail : salesContractDetails) {
				if (products[i] == salesContractDetail.getProduct()) {
					salesContractDetail.setReturnNum(salesContractDetail
							.getReturnNum()
							+ returnsNums[i]+returnResviceNum[i]);
					salesContractDetail.setNoReceiveNum(salesContractDetail.getNoReceiveNum()+returnsNums[i]);
					if (salesContractDetail.getReturnNum()
							- salesContractDetail.getContractNum() == 0) {
						salesContractDetail.setReturnSate(1);
						salesContractDetail.setRecivesState(1);
					}

				}
			}
		}
		for (int i = 0; i < returnResviceNum.length; i++) {
			if (returnResviceNum[i] != 0) {
				String[] details = detailAll[i].trim().split(",");
				for (int c = 0; c < details.length; c++) {
					String[] values = details[c].trim().split("p");
					SalesShippingDetail salesShippingDetail = this
							.getSalesShippingDetailService().get(
									Integer.parseInt(values[1].trim()));
					salesShippingDetail.setRetruenNum(salesShippingDetail
							.getRetruenNum()
							+ Integer.parseInt(values[0].trim()));
					if (salesShippingDetail.getNumber()
							- salesShippingDetail.getRetruenNum() == 0) {
						salesShippingDetail.setRetruenState(1);
					}
					this.getSalesShippingDetailService().save(
							salesShippingDetail);

				}
			}
		}
		
		for (SalesContractDetail salesContractDetail : salesContractDetails) {
			if (salesContractDetail.getReturnSate() != 1) {
				returnstate = false;
				break;
			}
		}
		if (returnstate) {
			salesContract.setReturnState(1);
			salesContract.setShippingState(1);
			salesContract.setReceiptState(1);
		}
		this.getSalesContractService().save(salesContract);
		super.save(returns);

	}

	public boolean valideSubmit(Returns entity) {

		return true;
	}

	public ReturnsService getReturnsService() {
		return returnsService;
	}

	public void setReturnsService(ReturnsService returnsService) {
		this.returnsService = returnsService;
	}

	@Override
	public Returns getReturnObject(Serializable id) {

		return this.getDao().getReturnObject(id);
	}

	@Override
	public void saveOrUpdate(Returns re) {
		this.getDao().saveOrUpdate(re);

	}

	@Override
	public Collection<Returns> getReturnsBysalesContract(
			SalesContract salesContract) {

		return this.getDao().getReturnsBysalesContract(salesContract);
	}

	public SalesContractService getSalesContractService() {
		return salesContractService;
	}

	public void setSalesContractService(
			SalesContractService salesContractService) {
		this.salesContractService = salesContractService;
	}

	public SalesShippingDetailService getSalesShippingDetailService() {
		return salesShippingDetailService;
	}

	public void setSalesShippingDetailService(
			SalesShippingDetailService salesShippingDetailService) {
		this.salesShippingDetailService = salesShippingDetailService;
	}

}
